from plugin import plugin

__doc__ = "todo"

class todo(plugin):
	"Todo plugin - Create todo lists!"
	
	def __init__(self):
		self._version = '3.0 testing'
		self.lists = {}
		if self._db:
			rows = self._db._exec("SELECT * FROM todo");
			if rows:
				for (nick, msg) in rows:
					self.__add(nick, msg)
	
	def __add(self, sender, msg):
		if sender not in self.lists:
			self.lists[sender] = []
		self.lists[sender].append(msg)

	def todo(self, msg, args):
		"Usage: .todo add [item name], .todo get, .todo remove [item], .todo clear"
		cmd, _, nargs = args.partition(' ')
		if cmd == '' or cmd.startswith('_'):
			self._irc.reply(msg, self.todo.__doc__)
		else:
			if hasattr(self, '_' + cmd):
				try: getattr(self, '_' + cmd)(msg, nargs)
				except: self._irc.reply(msg, self.todo.__doc__)
			else:
				self._irc.reply(msg, self.todo.__doc__)

	def _add(self, msg, args):
		sender = msg['sender']['name']
		self.__add(sender, args)
		if self._db:
			self._db._exec("INSERT INTO todo VALUES(%s, %s);", (sender, args))

	def _get(self, msg, args):
		sender = msg['sender']['name']
		if sender in self.lists:
			self._irc.reply(msg, ', '.join(self.lists[sender]))
		else:
			self._irc.reply(msg, 'You dont have anything todo!')

	def _remove(self, msg, args):
		sender = msg['sender']['name']
		if sender in self.lists:
			if args in self.lists[sender]:
				self.lists[sender].remove(args)
		if self._db:
			self._db._exec("DELETE FROM todo WHERE nick=%s AND item=%s;", (sender, args))

	def _clear(self, msg, args):
		sender = msg['sender']['name']
		if sender in self.lists:
			del self.lists[sender]
		if self._db:
			self._db._exec("DELETE FROM todo WHERE nick=%s;", (sender, ))
